<?php

namespace app\wechat\controller;

use think\Log;

class Index extends \think\Controller {

    public function __construct() {
        parent::__construct();
    }
    
    public function zcurl(){
        $request = request();
        $params = $request->param();
        
        $class = '\\app\\wechat\\controller\\' . ucfirst($params['c']);
        $obj = new $class();
        $result = call_user_func_array([$obj, $params['a']], [$params]);

        return $result;
    }

    //首页
    public function index() {
        if (!session('username')) {
            return view('pay/paylogin');
        }
        return view('user/msg');
    }

    //申请指南
    public function application() {
        return view('cooperation/application');
    }

    //申请指南
    public function payment() {
        return view('cooperation/payment');
    }

    //申请指南
    public function commonProblem() {
        return view('cooperation/qa');
    }
    
    /*
     *接收扫码信息
     */
    public function getQrcode(){
        $request = request();
        $params = $request->param();
        session('phone',$params['phone']);
        if($params['type']=='jiaoyu'){
            session('order_no',$params['order_no']);
            session('order_price',$params['order_price']);
            return redirect('/user/mechanism?partner_id='.$params['partner_no']);
        }else{
            session('b_id',$params['b_id']);
            session('partner_id',null);
        }
        
        if(!session('openid')){
            $result = $this->getWS('ucenter', 'users@checkUser', ['userName' => $params['phone']]);
            if($result['status'] == '5000' && !$result['result']['open_id']){
                $auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";
                $auth_url = sprintf($auth_url ,config('wechat.'. APP_ENV)['appid'] ,urlencode(config('wechat.'. APP_ENV)['weburl']. "/user.openid"), "snsapi_base", 200);
                return redirect($auth_url);
            }
        }
        $result = $this->getWS('credit', 'apply@applyStatus', ['b_id' =>  session('b_id')]);
        if($result['status'] == '2000'){
            if($result['result']['u_status'] == '1'){
                if($result['result']['status'] == '0000'){
                    return redirect('/user/submitmsg');
                }elseif($result['result']['status'] == '1000'){
                    return redirect('/order/submitorder');
                }else{
                    return redirect('/user/msg');
                }
            }else{
                return redirect('/user/register?phone='.$params['phone']);
            }
        }
    }
    
    //模板
    public function showtpl() {
        $request = request();
        $params = $request->param();

        if($params['n'] != 'partnerRegister'){
            if(!request()->isMobile()){
                die('<div style="text-align: center;">请您在手机端进行访问！</div>');
            }
        }
        
        // 获取学员状态
        $userStatus = $this->getWS('ucenter', 'Users@userStatus', ['userName'=>session('username')]);
        if($userStatus['status'] == '2000'){
            if($userStatus['result']['u_status'] != 1){
                session(null);
                return redirect('/payIndex');
            }
        }

        $title = [
            'msg' => '我的资料',
            'cardinfo' => '实名认证',
            'addmsg' => '个人信息',
            'bankcard' => '银行卡信息',
            'basicmsg' => '基本信息',
            'changephone' => '变更手机号',
            'contact' => '联系人信息',
            'findpassword' => '找回密码',
            'goapply' => '我的订单',
            'idcard' => '身份证照片',
            'login' => '登录',
            'mechanism' => '机构编号',
            'orderform' => '产品信息',
            'phonenum' => '手机号信息',
            'register' => '注册',
            'submitmsg' => '订单信息',
            'worklist' => '工作信息',
            'backorder' => '审核回退',
            'changeorder' => '审核回退',
            'jorderinfo' => '订单详情',
            'jsubmitorder' => '确认订单',
            'mypayment' => '我要缴费',
            'orderinfo' => '订单详情',
            'orderlist' => '我的订单',
            'ordersuccess' => '提交成功',
            'paymentplan' => '交费列表',
            'spaymentplan' => '交费列表',
            'submitorder' => '确认订单',
            'addbank' => '绑定银行卡',
            'addcard' => '实名认证',
            'addcontact' => '添加联系人',
            'adddaturm' => '上传资料',
            'adduinfo' => '基本信息',
            'addwork' => '工作信息',
            'authform' => '认证信息',
            'videoform' => '人脸识别',
            'addyys' => '服务密码',
            'addsms' => '短信验证码',
            'paylogin' => '登录',
            'payregister' => '注册',
            'payfindpassword' => '找回密码',
            'confirmOrder' => '确认订单',
            'partnerRegister' => '机构注册',
            'codelogin' => '验证码登录',
        ];
        config('title',$title[$params['n']]);
        if(in_array($params['n'],['register','login','paylogin','payregister','codelogin'])){
            if(!session('openid')){
                if(IsWeixinOrAlipay() == 'WeiXin') {
                    session('redirect_url', '/' . $params['d'] . '/' . $params['n']);
                    $auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";
                    $auth_url = sprintf($auth_url ,config('wechat.'. APP_ENV)['appid'] ,urlencode(config('wechat.'. APP_ENV)['weburl']. "/user.openid"), "snsapi_base", 200);
                    return redirect($auth_url);
                }
            }elseif (session('username') && session('partner_id')) {
                if(session('order_price')){
                    return redirect('/user/authform?order_price='.session('order_price'));
                }else{
                    return redirect('/user/authform');
                }
            }elseif(session('username')){
                return redirect('/user/msg');
            }
        }

        $tplname = $params['d'] . '/' . $params['n'];
        session('jump_url', !empty($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:'/user/msg');
        return view($tplname);
    }
    
    //接口统一入口请勿修改
    public function api() {
        $request = request();
        if ($request->isPost()) {
            $params = json_decode($request->param('datas'), true);
            if(!checkParam($params)){
                return $this->parse_data(['code' => 5000, 'msg' => '参数错误']);
            }
            $interface = $params['interface'];
            unset($params['interface']);
            list($c, $a) = explode('@', $interface);

            //判断是否登录验证
            if (!in_array($a, config('not_check_login'))) {
                if($a == 'payLogin' || $a == 'payRegister' ||$a == 'codeLogin' || $c == 'IcbcPay'){
                    if (!session('username')) {
                        return $this->parse_data(['code' => 5003, 'msg' => '请先登录']);
                    }
                }else{
                    if (!session('username')) {
                        return $this->parse_data(['code' => 5001, 'msg' => '请先登录']);
                    }
                }
            }
            $class = '\\app\\wechat\\controller\\' . ucfirst($c);
            $obj = new $class();
            $result = call_user_func_array([$obj, $a], [$params]);

            Log::write($result, '接口返回', true, 'interface/');

            return $result;
        }
    }
    
    /*
     * ESB请求
     */
    protected function getWS($sysSign, $interface, $params) {
        $s = new \SoapClient(config('esb.wsdl'));
        $soap_var = new \SoapVar(['authName' => config('esb.auth_name'), 'authPwd' => config('esb.auth_pwd')], SOAP_ENC_OBJECT, 'auth', 'mayi');
        $u = new \SoapHeader('mayi', 'auth', $soap_var, true);
        $s->__setSoapHeaders($u);
        $suc = $s->destInterface(config('esb.sys_sign'), $sysSign, $interface, json_encode($params));
        return json_decode($suc, true);
    }

    /*
     * 统一返回调用
     */
    protected function parse_data($result = []) {
        $tm = time();
        $retdata = [
            'status' => isset($result['code']) ? $result['code'] : 2000,
            'msg' => isset($result['msg']) ? $result['msg'] : '操作成功',
            'result' => isset($result['data']) ? $result['data'] : [],
            'runtime' => $tm,
        ];
        return json($retdata);
    }

}
